import cmdb.api.http_result as hh
from cmdb import models
from cmdb.util import http_util as hu
import uuid
import json
import redis
from cmdb.api.session import session_set
from cmdb.api.session import session_get


# 添加游戏
def add(req):

    hd = hu.json_obj(req)
    data = hd[0]
    if data:
        gid = uuid.uuid1()
        name = data.get('name', None)
        icon = data.get('icon', None)
        image = data.get('image', None)

        if not name:
            return hh.resp_result(0, "game's name is null")
        try:
            gg = models.Game.objects.get(name=name)
            gg.icon = icon
            gg.image = image
            gg.save()

        except:
            models.Game.objects.create(id=gid, name=name, icon=icon, image=image)

        return hh.resp_result(1, hh.RESULT_SUCCESS)
    else:
        return hh.resp_result(0, hh.RESULT_FAIL, {'error_info': hd[1]})


# 查询所有游戏
#   先从内存中查找, 找到就返回 否者从数据库中查找
def query_all(req):
    pool = redis.ConnectionPool(host='localhost', port=6379)
    r = redis.Redis(connection_pool=pool)
    games = r.get('games')
    if games:
        print('value from redis')
        return hh.resp_result(1, hh.RESULT_SUCCESS, games)

    print('value from db')
    # redis 中没有, 从数据库中查找
    rs = models.Game.objects.filter(status=1)
    if len(rs) > 0:
        games = []
        for gg in rs:
            dd = dict()
            dd['game_id'] = gg.id
            dd['name'] = gg.name
            dd['icon'] = gg.icon
            dd['image'] = gg.image
            games.append(dd)

        gs = json.dumps(games)
        # 保存到redis
        r.set('games', value=gs)
        return hh.resp_result(1, hh.RESULT_SUCCESS, gs)
    else:
        return hh.resp_result(1, 'there is no game to return')


# 获取游戏难度详情
def get_game_difficulty_detail(req):
    hd = hu.json_obj(req)
    data = hd[0]
    if data:
        # 游戏ID
        game_id = data.get('game_id', None)
        grade = data.get('grade', 0)

        if not game_id:
            return hh.resp_result(0, "game_id is null")
        try:
            details = models.GameDifficultyDetail.objects.filter(game_id=game_id, grade=grade)
            if len(details) > 0:
                gd = details.first()
                return hh.resp_result(1, hh.RESULT_SUCCESS, gd.detail)
            else:
                return hh.resp_result(0, 'game_id: %s, grade: %d  not found' % (game_id, grade))


        except BaseException as error:
            return hh.resp_result(0, hh.RESULT_FAIL, {hh.ERROR_INFO: error.__str__()})


    else:
        return hh.resp_result(0, hh.RESULT_FAIL, {'error_info': hd[1]})


